package com.css.fxfzysx.modules.ysxManagement.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.css.fxfzysx.base.response.RestResponse;
import com.css.fxfzysx.modules.vaolEngineering.repository.ValEngineeringRepository;
import com.css.fxfzysx.modules.vaolEngineering.utils.MainTableUtils;
import com.css.fxfzysx.modules.ysxManagement.entity.*;
import com.css.fxfzysx.modules.ysxManagement.repository.RdFactorRepository;
import com.css.fxfzysx.modules.ysxManagement.repository.ZqtCiRepository;
import com.css.fxfzysx.modules.ysxManagement.service.RdFactorService;
import com.css.fxfzysx.modules.ysxManagement.service.ZqtCiService;
import com.css.fxfzysx.modules.ysxManagement.vo.DdRatioVo;
import com.css.fxfzysx.modules.ysxManagement.vo.HaManageVo;
import com.css.fxfzysx.modules.ysxManagement.vo.RdFactorVo;
import com.css.fxfzysx.util.PlatformDateUtils;
import com.css.fxfzysx.util.PlatformObjectUtils;
import com.css.fxfzysx.util.PlatformSessionUtils;
import com.css.fxfzysx.util.UUIDGenerator;
import com.css.fxfzysx.web.PlatformSessionContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class RdFactorServiceImpl implements RdFactorService {

    @Autowired
    private RdFactorRepository rdFactorRepository;

    @Autowired
    private ZqtCiService zqtCiService;

    @Autowired
    private ZqtCiRepository zqtCiRepository;

    @Autowired
    private ValEngineeringRepository valEngineeringRepository;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public RestResponse saveOrUpdateRdFactor(List<RdFactorEntity> rdFactorEntityList) {
        try {
            if (PlatformObjectUtils.isNotEmpty(rdFactorEntityList)) {
                rdFactorEntityList.forEach(it -> {
                    if(PlatformObjectUtils.isEmpty(it.getCrdfId())){
                        it.setCrdfId(UUIDGenerator.getUUID());
                        it.setCreateUser(PlatformSessionContext.getUserID());
                        it.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
                        it.setDelFlag("0");
                        it.setDefaultData("1");
                        rdFactorRepository.saveRdFactor(it);
                    }else {
                        it.setUpdateUser(PlatformSessionUtils.getUserId());
                        it.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                        List<RdFactorEntity> list = rdFactorRepository.getRdById(it.getCrdfId());
                        list.forEach(rd->{
                            if (!rd.getQuantizedValue().equals(it.getQuantizedValue())){
                                valEngineeringRepository.updateCountStatusByModelIds1Id(it.getCrdfId());
                            }
                        });
                        rdFactorRepository.updateRdFactor(it);
                    }
                });
            }
            return RestResponse.succeed("成功!");
        } catch (Exception e) {
            String errorMessage = "失败!";
            log.error(errorMessage, e);
            return RestResponse.fail(errorMessage);
        }
    }

    @Override
    public RestResponse getAllRdFactor() {
        try {
            List<RdFactorEntity> rdFactorEntityList = rdFactorRepository.getAllRdFactor();
            Map<Integer, List<RdFactorEntity>> collect = rdFactorEntityList.stream().collect(Collectors.groupingBy(RdFactorEntity::getSerialNumber));
            Map<Integer, RdFactorEntity> result = new HashMap<>();
            collect.forEach((k, v) -> {
                RdFactorEntity rd = new RdFactorEntity();
                rd.setSerialNumber(k);
                rd.setSerialData(v);
                rd.setDamageFactor(v.get(0).getDamageFactor());
                result.put(k, rd);
            });
            return RestResponse.succeed(result);
        } catch (Exception e) {
            String errorMessage = "查询失败!";
            log.error(errorMessage, e);
            return RestResponse.fail(errorMessage);
        }
    }

    @Override
    public RestResponse deleteRdFactorById(String rdFactorIds) {
        try {
            boolean result = true;
            for (String rdFactorId : rdFactorIds.split(",")) {
                result = rdFactorRepository.deleteRdFactorById(rdFactorId);
            }
            if(result){
                return RestResponse.succeed("删除成功!");
            }else {
                return RestResponse.fail("删除失败!");
            }
        } catch (Exception e) {
            String errorMessage = "删除失败!";
            log.error(errorMessage, e);
            return RestResponse.fail(errorMessage);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public RestResponse saveOrUpdateDdRatio(DdRatioVo ddRatioVo) {
        try {
            List<DdRatioEntity> ddRatioList = ddRatioVo.getDdRatioList();
            List<DynamicFieldsEntity> dynamicFieldsList = ddRatioVo.getDynamicFieldsList();
            if (PlatformObjectUtils.isNotEmpty(ddRatioList)) {
                ddRatioList.forEach(it -> {
                    if(PlatformObjectUtils.isEmpty(it.getCddrId())){
                        it.setCddrId(UUIDGenerator.getUUID());
                        it.setCreateUser(PlatformSessionContext.getUserID());
                        it.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
                        it.setDelFlag("0");
                        it.setDefaultData("1");
                        rdFactorRepository.saveDdRatio(it);
                    }else {
                        it.setUpdateUser(PlatformSessionUtils.getUserId());
                        it.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                        List<DdRatioEntity> list = rdFactorRepository.getDdById(it.getCddrId());
                        list.forEach(dd->{
                            if (!dd.getDispersedRatio().equals(it.getDispersedRatio())){
                                valEngineeringRepository.updateCountStatusByModelIds2Id(it.getCddrId());
                            }
                        });
                        rdFactorRepository.updateDdRatio(it);
                    }
                });
            }
            zqtCiService.saveOrUpdateDynamicFields(dynamicFieldsList);
            return RestResponse.succeed("成功!");
        } catch (Exception e) {
            String errorMessage = "失败!";
            log.error(errorMessage, e);
            return RestResponse.fail(errorMessage);
        }
    }

    @Override
    public RestResponse getAllDdRatio(String titleName) {
        try {
            DdRatioVo ddRatioVo = new DdRatioVo();
            List<DdRatioEntity> ddRatioList = rdFactorRepository.getAllDdRatio();
            List<DynamicFieldsEntity> dynamicFields = zqtCiRepository.getDynamicFields(titleName);
            ddRatioVo.setDdRatioList(ddRatioList);
            ddRatioVo.setDynamicFieldsList(dynamicFields);
            return RestResponse.succeed(ddRatioVo);
        } catch (Exception e) {
            String errorMessage = "查询失败!";
            log.error(errorMessage, e);
            return RestResponse.fail(errorMessage);
        }
    }

    @Override
    public RestResponse deleteDdRatioById(String ddRatioIds,String arrangeIds) {
        try {
            if(PlatformObjectUtils.isNotEmpty(ddRatioIds)){
                for (String ddRatioId : ddRatioIds.split(",")) {
                    rdFactorRepository.deleteDdRatioById(ddRatioId);
                }
            }
            if(PlatformObjectUtils.isNotEmpty(arrangeIds)){
                for (String arrangeId : arrangeIds.split(",")) {
                    zqtCiRepository.deleteArrangeById(arrangeId);
                    rdFactorRepository.deleteDdRatioByProjectId(arrangeId);
                }
            }
            return RestResponse.succeed("删除成功!");
        } catch (Exception e) {
            String errorMessage = "删除失败!";
            log.error(errorMessage, e);
            return RestResponse.fail(errorMessage);
        }
    }
}
